package br.com.testepratico.model.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

public class HibernateDAO<T> implements InterfaceDAO<T> {

	private EntityManager manager;
	private Class<T> classe;

	public HibernateDAO(EntityManager manager, Class<T> classe) {
		this.manager = manager;
		this.classe = classe;
	}

	@Override
	public void adiciona(T bean) {
		manager.persist(bean);
	}

	@Override
	public void remove(Integer id) {
		T find = manager.find(classe, id);
		manager.remove(find);
	}

	@Override
	public void altera(T bean) {
		manager.merge(bean);
	}

	@Override
	public T getBean(Integer id) {
		String sql = "SELECT b FROM " + classe.getSimpleName() + " b WHERE b.id = :id";
		TypedQuery<T> query = manager.createQuery(sql, classe);
		query.setParameter("id", id);

		return query.getSingleResult();
	}

	@Override
	public List<T> getBeans() {
		String sql = "SELECT b FROM " + classe.getSimpleName() + " b";
		TypedQuery<T> query = manager.createQuery(sql, classe);

		return query.getResultList();
	}

	@Override
	public void setManager(EntityManager manager) {
		this.manager = manager;
	}

	protected EntityManager getManager() {
		return manager;
	}
}
